//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Web.UI;
using System.Web.UI.WebControls;

using CommunityServer.Components;
using CommunityServer.Controls;
using CommunityServer.Discussions.Components;

namespace CommunityServer.Discussions.Controls.PostDisplay 
{
    public class TextPost : TemplatedWebControl
    {
        #region Child Controls

        Literal body;
        Literal signature;
        Literal editNotes;

        CSContext csContext = CSContext.Current;
        ForumPost _post;

        #endregion

        protected override void OnInit(EventArgs e) 
        {
            if (SkinName == null)                
                ExternalSkinFileName = "PostType-TextPost.ascx";
            else 
                ExternalSkinFileName = SkinName;
			
            base.OnInit(e);
        }
		
        protected override void OnLoad(EventArgs e) 
        {
            DataBind();

            base.OnLoad(e);
        }

        #region DataBind

        public override void DataBind() 
        {
            base.DataBind();

            ForumPost post = this.Post;

            if (post == null)
                return;

			ForumConfiguration config = ForumConfiguration.Instance();
            
			// Register javascript file for the collapsing sections
			Page.RegisterClientScriptBlock( "CommunityServer.Controls.ExpanderPanel", String.Format( "<script type='text/javascript' language='javascript' src='{0}'></script>", Page.ResolveUrl( "~/Utility/ExpanderPanelScript.js" ) ) );
            
            // Inform the following controls that the user should be seen as anonymous
            //
            bool swowUserAsAnonymous = (post.IsAnonymousPost && 
                                        config.EnableUserPostingAsAnonymous && 
                                        post.Forum.EnableAnonymousPostingForUsers);

            if (body != null)
            {
                body.Text = post.RenderedBody(PostTarget.Web);
            
                // TODO eventually we'll add support for multiple attachments, this would need to be improved to handle more than 1 image attachment
                string fileName = post.AttachmentFilename;
                if (fileName != "" && 
                    fileName != null) 
                {
                    string fileExtension = fileName.Substring(fileName.LastIndexOf(".") + 1);
                    if (fileExtension != null && 
                        fileExtension != string.Empty) 
                    {
                        fileExtension = fileExtension.ToLower();

                        if (config.EnableInlinedImages) 
                        {
                            string supportedTypes = config.SupportedInlinedImageTypes;
                            if (supportedTypes != null && 
                                supportedTypes != string.Empty) 
                            {
                                string[] supportedImageTypes = supportedTypes.Split(';');

                                int height = config.InlinedImageHeight;
                                int width = config.InlinedImageWidth;

                                foreach (string imageType in supportedImageTypes) 
                                {
                                    if (fileExtension == imageType) 
                                    {

                                        // format the image element to constrain the height and width of the image, if the admin configures it
                                        body.Text += String.Format("<br /><a href='{0}' target='_blank'><img src='{1}' border='0' onload=\"{2}{3}\"></a>" 
                                            , ForumUrls.Instance().PostAttachment(post.PostID), ForumUrls.Instance().PostAttachment(post.PostID)
                                            , width != -1 ? String.Format("if(this.width>{0})this.width={0};", width ) : String.Empty
                                            , height != -1 ? String.Format("if(this.height>{0})this.height={0};", height ) : String.Empty );

                                        // break out of the for loop
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            if (signature != null && csContext.User.EnableUserSignatures)
            {
				if (post.Section == null && post.SectionID > 0)
					post.Section = Forums.GetForum(post.SectionID);

                // Set the user's formatted signature
                //
                if ((post.Section == null || post.Section.ForumType == ForumType.Normal) &&
                    csContext.SiteSettings.EnableUserSignatures &&
                    !swowUserAsAnonymous)
                {
                    signature.Text = Globals.FormatSignature( post.User.Profile.SignatureFormatted );
                }
            }


            if (editNotes != null)
            {
                // Construct the user object
                //
                User user = csContext.User;	

                if (ForumConfiguration.Instance().DisplayEditNotesInPost) 
                {
                    // TDD 3/18/2004
                    // This is another huge performance hit. Again we should only be processing the edit notes
                    // once when they are initially created not for each view of the post.
                    if (!user.IsAnonymous) 
                    {
                        if (user.IsForumAdministrator || user.IsModerator) 
                        {
                            if (post.EditNotes != null) 
                            {
                                string formattedNotes = Globals.HtmlNewLine + Globals.HtmlNewLine + Globals.HtmlNewLine + "<div width=\"100%\" class=\"txt3\">" + post.EditNotes + "</div>";
                                editNotes.Text = formattedNotes.Replace("\n", Globals.HtmlNewLine);
                            }
                        }
                    }
                }
            }
        }
		
        #endregion		
		
        #region Skin
                
        protected override void AttachChildControls() 
        {
            // Find the controls we need
            //
            body = FindControl("Body") as Literal;
            signature = FindControl("Signature") as Literal;
            editNotes = FindControl("EditNotes") as Literal;			
        }
		        
        #endregion

        #region Properties

        public ForumPost Post 
        {
            get 
            {
                if ( _post == null ) 
                {
                    Object state = ViewState["Post"];
                    if ( state != null ) 
                    {
                        Int32 postID = (Int32)state;
                        _post = Posts.GetPost( postID, csContext.User.UserID, false );
                    }
                }
                return _post;
            }
            set 
            {
                _post = value;
                if ( _post != null ) 
                {
                    ViewState[ "Post" ] = _post.PostID;
                } 
                else 
                {
                    ViewState.Remove( "Post" );
                }
            }
        }

        #endregion
    }
}
